package com.qf.qfzuul.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.pojo.R;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {
    //定义类型
    @Override
    public String filterType() {
        return "pre";
    }

    //定义执行时机，值越小，越优先
    @Override
    public int filterOrder() {
        return -5;
    }

    //定义哪些资源需要拦截
    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        HttpServletRequest request = currentContext.getRequest();

        String uri = request.getRequestURI();
        //判断是否是登录、注册相关资源，是 -- 不拦截（false）,不是 -- 拦截（true）


        //返回true，就会执行run方法
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        HttpServletRequest request = currentContext.getRequest();

        //解决响应乱码
        response.setContentType("application/json;charset=utf-8");

        //判断请求头中是否有token
        String token = request.getParameter("token");

        if (token != null){
            //校验token合法性
            System.out.println("合法....");
        }else{
            try {
                //没有携带，没有登录，不让访问资源,阻断继续路由
                currentContext.setSendZuulResponse(false);

                response.setStatus(401);
                R r = R.error().putMsg("尚未登录");
                response.getWriter().write(JSON.toJSONString(r));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //这个返回值没用
        return null;
    }
}
